

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=auto>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/img/fluid.png">
  <link rel="icon" href="/img/fluid.png">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="author" content="深海火锅店">
  <meta name="keywords" content="">
  
    <meta name="description" content="内置组件keep-alive有时候我们不希望组件被重新渲染影响使用体验；或者处于性能考虑，避免多次重复渲染降低性能。而是希望组件可以缓存下来,维持当前的状态。这时候就需要用到keep-alive组件。 开启keep-alive 生命周期的变化  初次进入时： onMounted&gt; onActivated 退出后触发 deactivated 再次进入只会触发 onActivated 事件挂载的">
<meta property="og:type" content="article">
<meta property="og:title" content="Hexo">
<meta property="og:url" content="http://example.com/2024/03/21/%E7%BC%96%E7%A8%8B%E8%AF%AD%E8%A8%80/Vue/Vue3/Vue3%E5%AD%A6%E4%B9%A0/15.keepalive%E7%BC%93%E5%AD%98%E7%BB%84%E4%BB%B6/index.html">
<meta property="og:site_name" content="Hexo">
<meta property="og:description" content="内置组件keep-alive有时候我们不希望组件被重新渲染影响使用体验；或者处于性能考虑，避免多次重复渲染降低性能。而是希望组件可以缓存下来,维持当前的状态。这时候就需要用到keep-alive组件。 开启keep-alive 生命周期的变化  初次进入时： onMounted&gt; onActivated 退出后触发 deactivated 再次进入只会触发 onActivated 事件挂载的">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2024-03-21T13:16:47.953Z">
<meta property="article:modified_time" content="2023-07-23T13:34:42.520Z">
<meta property="article:author" content="深海火锅店">
<meta name="twitter:card" content="summary_large_image">
  
  
    <meta name="referrer" content="no-referrer-when-downgrade">
  
  
  <title>Hexo</title>

  <link  rel="stylesheet" href="https://lib.baomitu.com/twitter-bootstrap/4.6.1/css/bootstrap.min.css" />



  <link  rel="stylesheet" href="https://lib.baomitu.com/github-markdown-css/4.0.0/github-markdown.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/hint.css/2.7.0/hint.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.css" />



<!-- 主题依赖的图标库，不要自行修改 -->
<!-- Do not modify the link that theme dependent icons -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_hj8rtnfg7um.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_lbnruvf0jn.css">


<link  rel="stylesheet" href="/css/main.css" />


  <link id="highlight-css" rel="stylesheet" href="/css/highlight.css" />
  
    <link id="highlight-css-dark" rel="stylesheet" href="/css/highlight-dark.css" />
  




  <script id="fluid-configs">
    var Fluid = window.Fluid || {};
    Fluid.ctx = Object.assign({}, Fluid.ctx)
    var CONFIG = {"hostname":"example.com","root":"/","version":"1.9.3","typing":{"enable":true,"typeSpeed":70,"cursorChar":"_","loop":false,"scope":[]},"anchorjs":{"enable":true,"element":"h1,h2,h3,h4,h5,h6","placement":"left","visible":"hover","icon":""},"progressbar":{"enable":true,"height_px":3,"color":"#29d","options":{"showSpinner":false,"trickleSpeed":100}},"code_language":{"enable":true,"default":"TEXT"},"copy_btn":true,"image_caption":{"enable":true},"image_zoom":{"enable":true,"img_url_replace":["",""]},"toc":{"enable":true,"placement":"right","headingSelector":"h1,h2,h3,h4,h5,h6","collapseDepth":0},"lazyload":{"enable":true,"loading_img":"/img/loading.gif","onlypost":false,"offset_factor":2},"web_analytics":{"enable":false,"follow_dnt":true,"baidu":null,"google":null,"gtag":null,"tencent":{"sid":null,"cid":null},"woyaola":null,"cnzz":null,"leancloud":{"app_id":null,"app_key":null,"server_url":null,"path":"window.location.pathname","ignore_local":false}},"search_path":"/local-search.xml"};

    if (CONFIG.web_analytics.follow_dnt) {
      var dntVal = navigator.doNotTrack || window.doNotTrack || navigator.msDoNotTrack;
      Fluid.ctx.dnt = dntVal && (dntVal.startsWith('1') || dntVal.startsWith('yes') || dntVal.startsWith('on'));
    }
  </script>
  <script  src="/js/utils.js" ></script>
  <script  src="/js/color-schema.js" ></script>
  


  
<meta name="generator" content="Hexo 6.3.0"></head>


<body>
  

  <header>
    

<div class="header-inner" style="height: 70vh;">
  <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand" href="/">
      <strong>Fluid</strong>
    </a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/">
                <i class="iconfont icon-home-fill"></i>
                首页
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/archives/">
                <i class="iconfont icon-archive-fill"></i>
                归档
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/categories/">
                <i class="iconfont icon-category-fill"></i>
                分类
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/tags/">
                <i class="iconfont icon-tags-fill"></i>
                标签
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/about/">
                <i class="iconfont icon-user-fill"></i>
                关于
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" target="_self" href="javascript:;" data-toggle="modal" data-target="#modalSearch" aria-label="Search">
              &nbsp;<i class="iconfont icon-search"></i>&nbsp;
            </a>
          </li>
          
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" target="_self" href="javascript:;" aria-label="Color Toggle">&nbsp;<i
                class="iconfont icon-dark" id="color-toggle-icon"></i>&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

  

<div id="banner" class="banner" parallax=true
     style="background: url('/img/background.jpg') no-repeat center center; background-size: cover;">
  <div class="full-bg-img">
    <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
      <div class="banner-text text-center fade-in-up">
        <div class="h2">
          
            <span id="subtitle" data-typed-text=""></span>
          
        </div>

        
          
  <div class="mt-3">
    
    
      <span class="post-meta">
        <i class="iconfont icon-date-fill" aria-hidden="true"></i>
        <time datetime="2024-03-21 21:16" pubdate>
          2024年3月21日 晚上
        </time>
      </span>
    
  </div>

  <div class="mt-1">
    
      <span class="post-meta mr-2">
        <i class="iconfont icon-chart"></i>
        
          4.6k 字
        
      </span>
    

    
      <span class="post-meta mr-2">
        <i class="iconfont icon-clock-fill"></i>
        
        
        
          39 分钟
        
      </span>
    

    
    
  </div>


        
      </div>

      
    </div>
  </div>
</div>

</div>

  </header>

  <main>
    
      

<div class="container-fluid nopadding-x">
  <div class="row nomargin-x">
    <div class="side-col d-none d-lg-block col-lg-2">
      

    </div>

    <div class="col-lg-8 nopadding-x-md">
      <div class="container nopadding-x-md" id="board-ctn">
        <div id="board">
          <article class="post-content mx-auto">
            <!-- SEO header -->
            <h1 style="display: none"></h1>
            
            
              <div class="markdown-body">
                
                <h1 id="内置组件keep-alive"><a href="#内置组件keep-alive" class="headerlink" title="内置组件keep-alive"></a><strong>内置组件keep-alive</strong></h1><p>有时候我们不希望组件被重新渲染影响使用体验；或者处于性能考虑，避免多次重复渲染降低性能。而是希望组件可以缓存下来,维持当前的状态。这时候就需要用到<code>keep-alive</code>组件。</p>
<p>开启keep-alive 生命周期的变化</p>
<ul>
<li>初次进入时： onMounted&gt; onActivated</li>
<li>退出后触发 <code>deactivated</code></li>
<li>再次进入只会触发 onActivated</li>
<li>事件挂载的方法等，只执行一次的放在 onMounted中；组件每次进去执行的方法放在 onActivated中</li>
</ul>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><code class="hljs xml"><span class="hljs-comment">&lt;!-- 基本 --&gt;</span><br><span class="hljs-tag">&lt;<span class="hljs-name">keep-alive</span>&gt;</span><br>  <span class="hljs-tag">&lt;<span class="hljs-name">component</span> <span class="hljs-attr">:is</span>=<span class="hljs-string">&quot;view&quot;</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">component</span>&gt;</span><br><span class="hljs-tag">&lt;/<span class="hljs-name">keep-alive</span>&gt;</span><br><br><span class="hljs-comment">&lt;!-- 多个条件判断的子组件 --&gt;</span><br><span class="hljs-tag">&lt;<span class="hljs-name">keep-alive</span>&gt;</span><br>  <span class="hljs-tag">&lt;<span class="hljs-name">comp-a</span> <span class="hljs-attr">v-if</span>=<span class="hljs-string">&quot;a &gt; 1&quot;</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">comp-a</span>&gt;</span><br>  <span class="hljs-tag">&lt;<span class="hljs-name">comp-b</span> <span class="hljs-attr">v-else</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">comp-b</span>&gt;</span><br><span class="hljs-tag">&lt;/<span class="hljs-name">keep-alive</span>&gt;</span><br><br><span class="hljs-comment">&lt;!-- 和 `&lt;transition&gt;` 一起使用 --&gt;</span><br><span class="hljs-tag">&lt;<span class="hljs-name">transition</span>&gt;</span><br>  <span class="hljs-tag">&lt;<span class="hljs-name">keep-alive</span>&gt;</span><br>    <span class="hljs-tag">&lt;<span class="hljs-name">component</span> <span class="hljs-attr">:is</span>=<span class="hljs-string">&quot;view&quot;</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">component</span>&gt;</span><br>  <span class="hljs-tag">&lt;/<span class="hljs-name">keep-alive</span>&gt;</span><br><span class="hljs-tag">&lt;/<span class="hljs-name">transition</span>&gt;</span><br></code></pre></td></tr></table></figure>

<p> <strong><code>include</code> 和 <code>exclude</code></strong></p>
<figure class="highlight elixir"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs elixir">&lt;keep-alive <span class="hljs-symbol">:include=<span class="hljs-string">&quot;&quot;</span></span> <span class="hljs-symbol">:exclude=<span class="hljs-string">&quot;&quot;</span></span> <span class="hljs-symbol">:max=<span class="hljs-string">&quot;&quot;</span>&gt;&lt;/keep-alive&gt;</span><br></code></pre></td></tr></table></figure>

<p>include 和 exclude 允许组件有条件地缓存。二者都可以用逗号分隔字符串、正则表达式或一个数组来表示：</p>
<p><strong><code>max</code></strong></p>
<figure class="highlight elixir"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs elixir">&lt;keep-alive <span class="hljs-symbol">:max=<span class="hljs-string">&quot;10&quot;</span>&gt;</span><br>  &lt;component <span class="hljs-symbol">:is=<span class="hljs-string">&quot;view&quot;</span>&gt;&lt;/component&gt;</span><br>&lt;/keep-alive&gt;<br></code></pre></td></tr></table></figure>

<h1 id="keep-alive-源码讲解"><a href="#keep-alive-源码讲解" class="headerlink" title="keep-alive 源码讲解"></a>keep-alive 源码讲解</h1><p>源码目录runtime-core&#x2F;src&#x2F;components&#x2F;KeepAlive.ts</p>
<h3 id="props"><a href="#props" class="headerlink" title="props"></a>props</h3><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><code class="hljs javascript"><span class="hljs-attr">props</span>: &#123;<br>   <span class="hljs-attr">include</span>: [<span class="hljs-title class_">String</span>, <span class="hljs-title class_">RegExp</span>, <span class="hljs-title class_">Array</span>], <span class="hljs-comment">// 配置了该属性，那么只有名称匹配的组件会被缓存</span><br>   <span class="hljs-attr">exclude</span>: [<span class="hljs-title class_">String</span>, <span class="hljs-title class_">RegExp</span>, <span class="hljs-title class_">Array</span>], <span class="hljs-comment">// 配置了该属性，那么任何名称匹配的组件都不会被缓存</span><br>   <span class="hljs-attr">max</span>: [<span class="hljs-title class_">String</span>, <span class="hljs-title class_">Number</span>]<span class="hljs-comment">// 最多可以缓存多少组件实例</span><br> &#125;,<br><br> <span class="hljs-title function_">setup</span>(<span class="hljs-params">props: KeepAliveProps, &#123; slots &#125;: SetupContext</span>) &#123;<br>   <span class="hljs-keyword">const</span> instance = <span class="hljs-title function_">getCurrentInstance</span>()!<br>   <span class="hljs-keyword">const</span> sharedContext = instance.<span class="hljs-property">ctx</span> <span class="hljs-keyword">as</span> <span class="hljs-title class_">KeepAliveContext</span><br> &#125;)<br>     <span class="hljs-keyword">const</span> &#123; include, exclude, max &#125; = props<br>       <span class="hljs-comment">//如果include 子组件名称 不包含， 和  exclude包含的名字 就不该缓存 直接返回</span><br>     <span class="hljs-keyword">if</span> (<br>       (include &amp;&amp; (!name || !<span class="hljs-title function_">matches</span>(include, name))) ||<br>       (exclude &amp;&amp; name &amp;&amp; <span class="hljs-title function_">matches</span>(exclude, name))<br>     ) &#123;<br>       current = vnode<br>       <span class="hljs-keyword">return</span> rawVNode<br>     &#125;<br></code></pre></td></tr></table></figure>

<figure class="highlight reasonml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><code class="hljs reasonml">watch(<br> <span class="hljs-function"> <span class="hljs-params">()</span> =&gt;</span> <span class="hljs-literal">[<span class="hljs-identifier">props</span>.<span class="hljs-identifier">include</span>, <span class="hljs-identifier">props</span>.<span class="hljs-identifier">exclude</span>]</span>,<br> <span class="hljs-function"> ([<span class="hljs-params">include</span>, <span class="hljs-params">exclude</span>]) =&gt;</span> &#123;<br>    <span class="hljs-comment">//props 是响应式的 所以这个操作需要在做一遍</span><br>    <span class="hljs-keyword">include</span><span class="hljs-operator"> &amp;&amp; </span>prune<span class="hljs-constructor">Cache(<span class="hljs-params">name</span> =&gt; <span class="hljs-params">matches</span>(<span class="hljs-params">include</span>, <span class="hljs-params">name</span>)</span>)<br>    exclude<span class="hljs-operator"> &amp;&amp; </span>prune<span class="hljs-constructor">Cache(<span class="hljs-params">name</span> =&gt; !<span class="hljs-params">matches</span>(<span class="hljs-params">exclude</span>, <span class="hljs-params">name</span>)</span>)<br>  &#125;,<br>  <span class="hljs-comment">// prune post-render after `current` has been updated</span><br>  &#123; flush: &#x27;post&#x27;, deep: <span class="hljs-literal">true</span> &#125;<br>)<br></code></pre></td></tr></table></figure>

<h3 id="缓存设计"><a href="#缓存设计" class="headerlink" title="缓存设计"></a>缓存设计</h3><figure class="highlight q"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br></pre></td><td class="code"><pre><code class="hljs q"> <span class="hljs-comment">//KeepAlive 组件的缓存管理</span><br> const cache: Cache = new Map()<br> const <span class="hljs-built_in">keys</span>: Keys = new Set()<br> let pendingCacheKey: CacheKey | <span class="hljs-built_in">null</span> = <span class="hljs-built_in">null</span><br> <span class="hljs-comment">//缓存函数</span><br> const cacheSubtree = () =&gt; &#123;<br>   <span class="hljs-comment">// fix #1621, the pendingCacheKey could be 0</span><br>   if (pendingCacheKey != <span class="hljs-built_in">null</span>) &#123;<br>     cache.<span class="hljs-built_in">set</span>(pendingCacheKey, getInnerChild(instance.subTree))<br>   &#125;<br> &#125;<br><br> <span class="hljs-comment">//KeepLive 组件中对缓存的管理时，首先会在组件的 onMounted 或 onUpdated 生命周期钩子函数中设置缓存，如下代码所示：</span><br> onMounted(cacheSubtree)<br> onUpdated(cacheSubtree)<br><span class="hljs-comment">//Vnode 的key 作为缓存的key</span><br>   pendingCacheKey = <span class="hljs-built_in">key</span><br>   <span class="hljs-comment">//KeepLive组件返回的函数中根据 vnode 对象的 key 去缓存中查找是否有缓存的组件，</span><br>    <span class="hljs-comment">//如果缓存存在，则继承组件实例，并将用于描述组件的 vnode 对象标记为 COMPONENT_KEPT_ALIVE，</span><br>    <span class="hljs-comment">//这样渲染器就不会重新创建新的组件实例；如果缓存不存在，则将 vnode 对象的key 添加到 keys 集合中</span><br>   if (cachedVNode) &#123;<br>     <span class="hljs-comment">// 如果缓存中存在缓存的组件</span><br>     vnode.el = cachedVNode.el<br>     vnode.component = cachedVNode.component<br>     <span class="hljs-comment">//无须创建组件实例，继承缓存的组件即可</span><br>     if (vnode.transition) &#123;<br>       <span class="hljs-comment">// 如果组件上有动画，处理动画</span><br>       setTransitionHooks(vnode, vnode.transition!)<br>     &#125;<br>     <span class="hljs-comment">// 标记Vnode 不会重新渲染</span><br>     vnode.shapeFlag |= ShapeFlags.COMPONENT_KEPT_ALIVE<br>     <span class="hljs-comment">// make this key the freshest</span><br>     <span class="hljs-built_in">keys</span>.<span class="hljs-keyword">delete</span>(<span class="hljs-built_in">key</span>)<br>     <span class="hljs-built_in">keys</span>.add(<span class="hljs-built_in">key</span>)<br>   &#125; else &#123;<br>     <span class="hljs-comment">//将 vnode 的key 添加到 keys 集合中，keys 集合用户维护缓存组件的 key</span><br>     <span class="hljs-built_in">keys</span>.add(<span class="hljs-built_in">key</span>)<br>     <span class="hljs-comment">// prune oldest entry</span><br>     if (<span class="hljs-built_in">max</span> &amp;&amp; <span class="hljs-built_in">keys</span>.size &gt; parseInt(<span class="hljs-built_in">max</span> as <span class="hljs-built_in">string</span>, <span class="hljs-number">10</span>)) &#123;<br>       pruneCacheEntry(<span class="hljs-built_in">keys</span>.values().<span class="hljs-built_in">next</span>().<span class="hljs-built_in">value</span>)<br>     &#125;<br>   &#125;<br></code></pre></td></tr></table></figure>

<h3 id="生命周期"><a href="#生命周期" class="headerlink" title="生命周期"></a>生命周期</h3><figure class="highlight reasonml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br></pre></td><td class="code"><pre><code class="hljs reasonml"><span class="hljs-comment">//隐藏容器</span><br> const storageContainer = create<span class="hljs-constructor">Element(&#x27;<span class="hljs-params">div</span>&#x27;)</span><br> <span class="hljs-comment">//在实例上注册两个钩子函数 activate，  deactivate</span><br> sharedContext.activate =<span class="hljs-function"> (<span class="hljs-params">vnode</span>, <span class="hljs-params">container</span>, <span class="hljs-params">anchor</span>, <span class="hljs-params">isSVG</span>, <span class="hljs-params">optimized</span>) =&gt;</span> &#123;<br>   const instance = vnode.component!<br>   move(vnode, container, anchor, MoveType.ENTER, parentSuspense)<br>   <span class="hljs-comment">// props 可能会发生变化，因此需要执行 patch 过程</span><br>   patch(<br>     instance.vnode,<br>     vnode,<br>     container,<br>     anchor,<br>     instance,<br>     parentSuspense,<br>     isSVG,<br>     vnode.slotScopeIds,<br>     optimized<br>   )<br>   queue<span class="hljs-constructor">PostRenderEffect(()</span> =&gt; &#123;<br>     instance.isDeactivated = <span class="hljs-literal">false</span><br>     <span class="hljs-keyword">if</span> (instance.a) &#123;<br>       invoke<span class="hljs-constructor">ArrayFns(<span class="hljs-params">instance</span>.<span class="hljs-params">a</span>)</span><br>     &#125;<br>     const vnodeHook = vnode.props<span class="hljs-operator"> &amp;&amp; </span>vnode.props.onVnodeMounted<br>     <span class="hljs-keyword">if</span> (vnodeHook) &#123;<br>       invoke<span class="hljs-constructor">VNodeHook(<span class="hljs-params">vnodeHook</span>, <span class="hljs-params">instance</span>.<span class="hljs-params">parent</span>, <span class="hljs-params">vnode</span>)</span><br>     &#125;<br>   &#125;, parentSuspense)<br><br>   <span class="hljs-keyword">if</span> (__DEV__<span class="hljs-operator"> || </span>__FEATURE_PROD_DEVTOOLS__) &#123;<br>     <span class="hljs-comment">// Update components tree</span><br>     devtools<span class="hljs-constructor">ComponentAdded(<span class="hljs-params">instance</span>)</span><br>   &#125;<br> &#125;<br><br> sharedContext.deactivate =<span class="hljs-function"> (<span class="hljs-params">vnode</span>: VN<span class="hljs-params">ode</span>) =&gt;</span> &#123;<br>   const instance = vnode.component!<br>   <span class="hljs-comment">//将组件移动到隐藏容器中</span><br>   <span class="hljs-comment">//在 “卸载” 组件时，并不是真正的卸载，而是调用 move 方法，将组件搬运到一个隐藏的容器中</span><br>   move(vnode, storageContainer, null, MoveType.LEAVE, parentSuspense)<br>   queue<span class="hljs-constructor">PostRenderEffect(()</span> =&gt; &#123;<br>     <span class="hljs-keyword">if</span> (instance.da) &#123;<br>       invoke<span class="hljs-constructor">ArrayFns(<span class="hljs-params">instance</span>.<span class="hljs-params">da</span>)</span><br>     &#125;<br>     const vnodeHook = vnode.props<span class="hljs-operator"> &amp;&amp; </span>vnode.props.onVnodeUnmounted<br>     <span class="hljs-keyword">if</span> (vnodeHook) &#123;<br>       invoke<span class="hljs-constructor">VNodeHook(<span class="hljs-params">vnodeHook</span>, <span class="hljs-params">instance</span>.<span class="hljs-params">parent</span>, <span class="hljs-params">vnode</span>)</span><br>     &#125;<br>     instance.isDeactivated = <span class="hljs-literal">true</span><br>   &#125;, parentSuspense)<br><br>   <span class="hljs-keyword">if</span> (__DEV__<span class="hljs-operator"> || </span>__FEATURE_PROD_DEVTOOLS__) &#123;<br>     <span class="hljs-comment">// Update components tree</span><br>     devtools<span class="hljs-constructor">ComponentAdded(<span class="hljs-params">instance</span>)</span><br>   &#125;<br> &#125;<br></code></pre></td></tr></table></figure>


                
              </div>
            
            <hr/>
            <div>
              <div class="post-metas my-3">
  
  
</div>


              
  

  <div class="license-box my-3">
    <div class="license-title">
      <div></div>
      <div>http://example.com/2024/03/21/编程语言/Vue/Vue3/Vue3学习/15.keepalive缓存组件/</div>
    </div>
    <div class="license-meta">
      
        <div class="license-meta-item">
          <div>作者</div>
          <div>深海火锅店</div>
        </div>
      
      
        <div class="license-meta-item license-meta-date">
          <div>发布于</div>
          <div>2024年3月21日</div>
        </div>
      
      
      
        <div class="license-meta-item">
          <div>许可协议</div>
          <div>
            
              
              
                <a target="_blank" href="https://creativecommons.org/licenses/by/4.0/">
                  <span class="hint--top hint--rounded" aria-label="BY - 署名">
                    <i class="iconfont icon-by"></i>
                  </span>
                </a>
              
            
          </div>
        </div>
      
    </div>
    <div class="license-icon iconfont"></div>
  </div>



              
                <div class="post-prevnext my-3">
                  <article class="post-prev col-6">
                    
                    
                      <a href="/2024/03/21/%E7%BC%96%E7%A8%8B%E8%AF%AD%E8%A8%80/Vue/Vue3/Vue3%E5%AD%A6%E4%B9%A0/14.Teleport%E4%BC%A0%E9%80%81%E7%BB%84%E4%BB%B6/" title="">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile"></span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/2024/03/04/%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84%E4%B8%8E%E7%AE%97%E6%B3%95/%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84%E4%B8%8E%E7%AE%97%E6%B3%95/" title="数据结构与算法">
                        <span class="hidden-mobile">数据结构与算法</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
          </article>
        </div>
      </div>
    </div>

    <div class="side-col d-none d-lg-block col-lg-2">
      
  <aside class="sidebar" style="margin-left: -1rem">
    <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;目录</p>
  <div class="toc-body" id="toc-body"></div>
</div>



  </aside>


    </div>
  </div>
</div>





  



  



  



  



  







    

    
      <a id="scroll-top-button" aria-label="TOP" href="#" role="button">
        <i class="iconfont icon-arrowup" aria-hidden="true"></i>
      </a>
    

    
      <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v" for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>

    

    
  </main>

  <footer>
    <div class="footer-inner">
  
    <div class="footer-content">
       <a href="https://hexo.io" target="_blank" rel="nofollow noopener"><span>Hexo</span></a> <i class="iconfont icon-love"></i> <a href="https://github.com/fluid-dev/hexo-theme-fluid" target="_blank" rel="nofollow noopener"><span>Fluid</span></a> 
    </div>
  
  
    <div class="statistics">
  
  

  
    
      <span id="busuanzi_container_site_pv" style="display: none">
        总访问量 
        <span id="busuanzi_value_site_pv"></span>
         次
      </span>
    
    
      <span id="busuanzi_container_site_uv" style="display: none">
        总访客数 
        <span id="busuanzi_value_site_uv"></span>
         人
      </span>
    
    
  
</div>

  
  
  
</div>

  </footer>

  <!-- Scripts -->
  
  <script  src="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.js" ></script>
  <link  rel="stylesheet" href="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.css" />

  <script>
    NProgress.configure({"showSpinner":false,"trickleSpeed":100})
    NProgress.start()
    window.addEventListener('load', function() {
      NProgress.done();
    })
  </script>


<script  src="https://lib.baomitu.com/jquery/3.6.0/jquery.min.js" ></script>
<script  src="https://lib.baomitu.com/twitter-bootstrap/4.6.1/js/bootstrap.min.js" ></script>
<script  src="/js/events.js" ></script>
<script  src="/js/plugins.js" ></script>


  <script  src="https://lib.baomitu.com/typed.js/2.0.12/typed.min.js" ></script>
  <script>
    (function (window, document) {
      var typing = Fluid.plugins.typing;
      var subtitle = document.getElementById('subtitle');
      if (!subtitle || !typing) {
        return;
      }
      var text = subtitle.getAttribute('data-typed-text');
      
        typing(text);
      
    })(window, document);
  </script>




  
    <script  src="/js/img-lazyload.js" ></script>
  




  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/tocbot/4.18.2/tocbot.min.js', function() {
    var toc = jQuery('#toc');
    if (toc.length === 0 || !window.tocbot) { return; }
    var boardCtn = jQuery('#board-ctn');
    var boardTop = boardCtn.offset().top;

    window.tocbot.init(Object.assign({
      tocSelector     : '#toc-body',
      contentSelector : '.markdown-body',
      linkClass       : 'tocbot-link',
      activeLinkClass : 'tocbot-active-link',
      listClass       : 'tocbot-list',
      isCollapsedClass: 'tocbot-is-collapsed',
      collapsibleClass: 'tocbot-is-collapsible',
      scrollSmooth    : true,
      includeTitleTags: true,
      headingsOffset  : -boardTop,
    }, CONFIG.toc));
    if (toc.find('.toc-list-item').length > 0) {
      toc.css('visibility', 'visible');
    }

    Fluid.events.registerRefreshCallback(function() {
      if ('tocbot' in window) {
        tocbot.refresh();
        var toc = jQuery('#toc');
        if (toc.length === 0 || !tocbot) {
          return;
        }
        if (toc.find('.toc-list-item').length > 0) {
          toc.css('visibility', 'visible');
        }
      }
    });
  });
</script>


  <script src=https://lib.baomitu.com/clipboard.js/2.0.11/clipboard.min.js></script>

  <script>Fluid.plugins.codeWidget();</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/anchor-js/4.3.1/anchor.min.js', function() {
    window.anchors.options = {
      placement: CONFIG.anchorjs.placement,
      visible  : CONFIG.anchorjs.visible
    };
    if (CONFIG.anchorjs.icon) {
      window.anchors.options.icon = CONFIG.anchorjs.icon;
    }
    var el = (CONFIG.anchorjs.element || 'h1,h2,h3,h4,h5,h6').split(',');
    var res = [];
    for (var item of el) {
      res.push('.markdown-body > ' + item.trim());
    }
    if (CONFIG.anchorjs.placement === 'left') {
      window.anchors.options.class = 'anchorjs-link-left';
    }
    window.anchors.add(res.join(', '));

    Fluid.events.registerRefreshCallback(function() {
      if ('anchors' in window) {
        anchors.removeAll();
        var el = (CONFIG.anchorjs.element || 'h1,h2,h3,h4,h5,h6').split(',');
        var res = [];
        for (var item of el) {
          res.push('.markdown-body > ' + item.trim());
        }
        if (CONFIG.anchorjs.placement === 'left') {
          anchors.options.class = 'anchorjs-link-left';
        }
        anchors.add(res.join(', '));
      }
    });
  });
</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.js', function() {
    Fluid.plugins.fancyBox();
  });
</script>


  <script>Fluid.plugins.imageCaption();</script>

  <script  src="/js/local-search.js" ></script>

  <script defer src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js" ></script>




  
<script src="//cdn.jsdelivr.net/gh/EmoryHuang/BlogBeautify@1.1/DynamicRibbon.min.js"></script>



<!-- 主题的启动项，将它保持在最底部 -->
<!-- the boot of the theme, keep it at the bottom -->
<script  src="/js/boot.js" ></script>


  

  <noscript>
    <div class="noscript-warning">博客在允许 JavaScript 运行的环境下浏览效果更佳</div>
  </noscript>
</body>
</html>
